package com.c1.client.dialog;

import com.google.common.collect.Maps;
import lombok.Setter;

import javax.swing.*;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Map;

public abstract class JDialogButtonSupport extends JDialog {
    public abstract List<Class<? extends BaseButton>> getBaseButton();

    private final Map<String, BaseButton> baseButtonMap = Maps.newHashMap();
    private final Map<Class<? extends BaseButton>, BaseButton> baseButtonClsMap = Maps.newHashMap();
    @Setter
    private ActionListener actionListener;

    public JDialogButtonSupport() {
        for (Class<? extends BaseButton> cls : getBaseButton()) {
            BaseButton button;
            try {
                button = cls.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            baseButtonMap.put(button.getText(), button);
            baseButtonClsMap.put(cls, button);
        }
    }

    public boolean process(String command) {
        BaseButton baseButton = baseButtonMap.get(command);
        if (baseButton != null) {
            baseButton.process();
            return true;
        }
        return false;
    }

    public <T extends BaseButton> JButton get(Class<T> cls) {
        BaseButton baseButton = baseButtonClsMap.get(cls);
        return baseButton.get(actionListener);
    }

    public <T extends BaseButton> JButton get(Class<T> cls, int mnemonic) {
        BaseButton baseButton = baseButtonClsMap.get(cls);
        return baseButton.get(actionListener, mnemonic);
    }

}
